package com.yixun.qfbao.api.service.impl;

import com.yixun.qfbao.api.service.SyncFollowAndAffixService;
import com.yixun.qfbao.api.service.WxTemplateMsgService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.mapper.AffixMapper;
import com.yixun.qfbao.model.Affix;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.dto.DictionaryDto;
import com.yixun.qfbao.model.dto.ReportExternalDto;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.model.enums.*;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.AffixConvert;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.SMSUtil;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.model.CaseMember;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.FollowUpList;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.FollowUpListDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.FollowUpListService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;



@Service("syncFollowAndAffixService")
public class SyncFollowAndAffixServiceImpl implements SyncFollowAndAffixService{
	
	private static Logger logger = LoggerFactory.getLogger(SyncFollowAndAffixServiceImpl.class);
	
	@Autowired
	private CustomerPremisesService customerPremisesService;
	
	@Autowired
	private ReportExternalService reportExternalService;
	
	@Autowired
	private FollowUpListService followUpListService;
	
	
	
	@Autowired
	private SmsSettingService smsSettingService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private CaseMemberService caseMemberService;
	
	@Autowired
	private DictionaryService dictionaryService;
	
	@Autowired
	private SmsHistoryService smsHistoryService;
	
	@Autowired
	private PartnerInfoService partnerInfoService;
	
	@Autowired
	private PremisesService premisesService;

	@Autowired
	private WxTemplateMsgService wxTemplateMsgService;
	@Autowired
	private SMSUtil smsUtil;
	
	@Autowired
	private AffixMapper affixMapper;

	@Autowired
	private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;

	@Override
	@Transactional
	public SyncFollowResDto syncFollow(SyncFollowReqDto reqDto) {
		
		SyncFollowResDto resDto=new SyncFollowResDto();
		resDto.setResult(ResultEnum.FAIL.getNo());
	
		try{
			
			//查询报备关联信息
			ReportExternalDto reportExternalDto=reportExternalService.getReportExternal(reqDto.getFirsthandIntentionUuid(),reqDto.getSysId());
			//判断是否为空
			if(null==reportExternalDto){
				resDto.setResultMsg("报备信息不存在，无法同步跟进!");
				return resDto;
			}
			
			//查询报备信息
			CustomerPremises customerPremises=customerPremisesService.selectById(reportExternalDto.getReportId());
			
			if(null==customerPremises){
				resDto.setResultMsg("报备信息不存在，无法同步跟进!");
				return resDto;
			}
			
			
			//写跟进
			String oldConfirmStatus = customerPremises.getConfirmStatus();
			String newConfirmStatus = customerPremises.getConfirmStatus();
			String oldCustomerStatus = customerPremises.getCustomerStatus();
			String newCustoemrStatus = customerPremises.getCustomerStatus();
			String commissionStatus = customerPremises.getCommissionStatus();
			// 新增跟进信息
			FollowUpListDto follow = new FollowUpListDto();
			follow.setStaffId(customerPremises.getStaffId());
			follow.setCustomerPremisesId(customerPremises.getId());
			follow.setOldConfirmStatus(oldConfirmStatus);
			follow.setNewConfirmStatus(newConfirmStatus);
			follow.setOldCustomerStatus(oldCustomerStatus);
			follow.setNewCustomerStatus(newCustoemrStatus);
			follow.setNewCommissionStatus(commissionStatus);
			follow.setOldCommissionStatus(commissionStatus);
			String remark= reqDto.getRemark();
			if(null==remark){
				remark="";
			}
			String operFollowRemark = "【" + "到访审核提醒"+ "】" + remark;
			follow.setRemark(operFollowRemark);
			follow.setFollowType(FollowTypeEnum.DEVELOPERS.getNo());
			follow.setFirsthandFollowUuid(reqDto.getFirsthandFollowUuid());
			follow.setAdviser(reqDto.getAdviser());
			follow.setVisitTime(DateUtils.StringToDate(reqDto.getVisitTime(),"yyyy-MM-dd HH:mm:ss"));
			follow = followUpListService.create(follow);
			
			
			//获取报备人信息
			PartnerInfo agentPi = partnerInfoService.selectById(customerPremises.getStaffId());
			if(null == agentPi){
				resDto.setResultMsg("报备经纪人未找到!");
				return resDto;
			}
			//判断是否为空
			Premises premises = premisesService.selectSimpleById(customerPremises.getPremisesId());
			if(null == premises){
				resDto.setResultMsg("此楼盘不存在，无法同步跟进!");
				return resDto;
			}
			
			Map<String, String> smsMap = new HashMap<String, String>();
			smsMap.put("premisesName", premises.getName());
			smsMap.put("adviser", reqDto.getAdviser());
			smsMap.put("visitTime", reqDto.getVisitTime());
			//给案场驻守人员发送短信
			sendReportSms(agentPi,customerPremises,smsMap);
			//给案场发送微信消息
			sendWxForNoticeAudit(premises,customerPremises);
		}catch(Exception e){
			logger.error("SyncFollowAndAffixServiceImpl ==> syncFollow error: {}", e);
			resDto.setResultMsg("同步跟进和附件失败: " + e.getMessage());
			return resDto;
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg("success");
		return resDto;
	}
	
	public void sendReportSms(PartnerInfo assistantPi, CustomerPremises customerPremises,Map<String,String> smsMap) {
		//查询楼盘相关案场助手人员,发短信用
    	CaseMemberDto cmDto = new CaseMemberDto();
    	cmDto.setPremisesId(customerPremises.getPremisesId());
    	cmDto.setPiStatus(MechanismStatusEnum.enable.getNo());
		cmDto.setSmsStatus("1");
    	List<CaseMember> cmList = new ArrayList<CaseMember>();
    	
		// 入参的是经纪人,非巧渠道人员.
		// 不能使用经纪人公司获取短信开关设置
		// 从楼盘重新获取
    	Premises premises = premisesService.selectSimpleById(customerPremises.getPremisesId());
		boolean flag = companyService.getMessageFlag(premises.getCompanyId());
    	logger.info("商户 [ " + assistantPi.getHigherid() + "], 短信通道是否打开: " + flag);
    	if(flag){
    		//需要发短信，就查询接收短信相关人员
    		cmList = caseMemberService.selectListByDto(cmDto);
    	}
    	
    	//发送短信
		try{
			if(!CollectionUtils.isEmpty(cmList)){
				//报备客户,给楼盘对应的管理员发送短信
	        	String smsSwitch = smsUtil.getSmsSwitch();
	        	if(StringUtils.isNotEmpty(smsSwitch) && "T".equals(smsSwitch)){
	        		
	        		String smsTemp = SMSTypeEnum.TYPE_15.getNo();
	        		DictionaryDto dicDto = new DictionaryDto();
	        		dicDto.setDicType(smsTemp);
	        		Dictionary dic = dictionaryService.selectByDto(dicDto);
	        		if(null != dic){
	        			for(CaseMember cm: cmList){
    	        			
    	        			String receiveMobile = "";
    	        			PartnerInfo cmPi = partnerInfoService.selectById(cm.getPartnerId());
    	        			if(null != cmPi){
    	        				receiveMobile = cmPi.getPhone();
    	        			}
    	        			if(StringUtils.isEmpty(receiveMobile)){
    	        				continue;
    	        			}
    	        			String smsContent = dic.getDicValue();
    	        			
    	        			String name=customerPremises.getName();//客户姓名
    	        			String mobile=customerPremises.getMobile();//客户手机号
    	        			String premisesName=smsMap.get("premisesName");//带看项目名称
    	        			String staffName=assistantPi.getAccountName();//经济人姓名
    	        			String staffMobile=assistantPi.getPhone();//经济人电话
    	        			String adviser=smsMap.get("adviser");
                            String visitTime=smsMap.get("visitTime");
                            if(StringUtils.isBlank(adviser)){
                            	adviser="--";
                            }
                            if(StringUtils.isBlank(visitTime)){
                            	visitTime="--";
                            }else{
                            	if(visitTime.length()>3){
                            		visitTime=visitTime.substring(0, visitTime.length()-3);
                            	}
                            }
    	        			smsContent = String.format(smsContent,name, mobile,visitTime, premisesName, adviser, staffName, staffMobile);

							//获取短信设置,功能已变更.设置已用于定制化号码验真.此处不能保留
							Map<String, String> smsSettingMap = null;
//    	                	Map<String, String> smsSettingMap = smsSettingService.getSmsSettingMap(null, cm.getCompanyId(),null);
    	                	Map<String,String> qfSmsMap = new HashMap<>();
    	                	qfSmsMap.put("key1",name);
    	                	qfSmsMap.put("key2",mobile);
    	                	qfSmsMap.put("key3",visitTime);
    	                	qfSmsMap.put("key4",premisesName);
    	                	qfSmsMap.put("key5",adviser);
    	                	qfSmsMap.put("key6",staffName);
    	                	qfSmsMap.put("key7",staffMobile);

							Map<String, Object> returnMap = smsUtil.sendMessage(smsContent, receiveMobile, QfSmsTemplateEnum.SMS_WARN_AUDIT.getId(), smsSettingMap,qfSmsMap);
							boolean sendStatus = (Boolean) returnMap.get("sendStatus");
							String sendRes = String.valueOf(returnMap.get("sendRes"));
    	        			SmsHistoryDto smsHis = new SmsHistoryDto();
    	        			smsHis.setSender(smsUtil.getUserName());
    	        			if(null != smsSettingMap) {
    	        				smsHis.setSender(smsSettingMap.get("userName"));
    	        			}
    	        			smsHis.setReceiver(receiveMobile);
    	        			smsHis.setContent(smsContent);
    	        			smsHis.setSendStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
							smsHis.setSendRes(sendRes);
    	        			smsHis.setMerchantId(cmPi.getHigherid());
    	        			smsHis.setRemark("提醒到访审核!");
    	        			smsHis.setCreateUserId(assistantPi.getId());
							if(returnMap.containsKey("orderUuid")){
								smsHis.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
							}
							if(returnMap.containsKey("platform")){
								smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
							}
    	        			smsHistoryService.create(smsHis);
	        			}
	        		}
    			}
			}
		}catch(Exception e){
			logger.error("SyncFollowAndAffixServiceImpl ==> sendReportSms error: {}", e);
		}
	}

	public void sendWxForNoticeAudit(Premises premises,CustomerPremises customerPremises){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//获取楼盘公司信息
		Company company = companyService.selectById(premises.getCompanyId());
		if(company == null ){
			throw new TServerException("公司信息不存在");
		}
		String token = wxAccessTokenCacheUtils.getAccessToken(company.getCompanyUuid(), SystemIdEnum.ASSISTANT.getCode(), company.getDomain());
		wxTemplateMsgService.sendVisitCheckTemplateMsg(token, company.getCompanyUuid()
				,company.getDomain(), customerPremises.getId(), premises.getId().toString(), customerPremises.getStaffId().toString()
				,customerPremises.getName(), customerPremises.getMobile(), customerPremises.getHopeVisitTime() == null ? "" : sdf.format(customerPremises.getHopeVisitTime()));
	}

	@Override
	public SyncAffixResDto syncAffix(SyncAffixReqDto reqDto) {
		SyncAffixResDto resDto=new SyncAffixResDto();
		resDto.setResult(ResultEnum.FAIL.getNo());
		//查询报备关联信息
		ReportExternalDto reportExternalDto=reportExternalService.getReportExternal(reqDto.getFirsthandIntentionUuid(),reqDto.getSysId());
		//判断是否为空
		if(null==reportExternalDto){
			resDto.setResultMsg("关联报备信息不存在，同步附件失败");
			return resDto;
		}
		
		//查询报备信息
		CustomerPremises customerPremises=customerPremisesService.selectById(reportExternalDto.getReportId());
		if(null==customerPremises){
			resDto.setResultMsg("报备信息不存在，同步附件失败");
			return resDto;
		}
		//查询跟进信息
		FollowUpList followUpList=followUpListService.selectByFirsthandFollowUuid(reqDto.getFirsthandFollowUuid());
		if(null==followUpList){
			resDto.setResultMsg("跟进信息不存在，同步附件失败");
			return resDto;
		}
		//保存附件
		if(!CollectionUtils.isEmpty(reqDto.getAffixList())){
			List<SyncAffixDto> dtoList=reqDto.getAffixList();
			try{
				if(!CollectionUtils.isEmpty(dtoList)){
					List<Affix> affixList=new  ArrayList<Affix>();
					Affix affix=null;
					for(SyncAffixDto dto:dtoList){
						affix=AffixConvert.convertSyncDTO2Model(dto);
						affix.setReportId(customerPremises.getId());
						affix.setFollowUpListId(followUpList.getId());
						affix.setCreatedTime(new Date());
						affix.setAffixUuid(UUID.randomUUID().toString());
						affixList.add(affix);
					}
					
					affixMapper.addAffixBatch(affixList);
				}
			}catch(Exception e){
				logger.error("SyncFollowAndAffixServiceImpl ==> syncAffix error: {}", e);
				resDto.setResultMsg("同步附件失败: " + e.getMessage());
				return resDto;
			}
			
		}
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setResultMsg("success");
		return resDto;
	}
	

}
